import "package:ct_pa_majordomo/pages/check_in_detail/api.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:flutter/material.dart";

class ElectricityUseRecord extends StatefulWidget {
  final int roomId;
  const ElectricityUseRecord({super.key, required this.roomId});

  @override
  State<ElectricityUseRecord> createState() => _ElectricityUseRecordState();
}

class _ElectricityUseRecordState extends State<ElectricityUseRecord> {
  DateTime _selectedDate = DateTime.now();
  String _selectedType = "年"; // 当前选择的类型：年、月、日

  // 列表数据
  List<Map<String, dynamic>> _records = [];
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _fetchRecords();
  }

  // 获取用电记录数据
  Future<void> _fetchRecords() async {
    if (_isLoading) return;
    setState(() {
      _isLoading = true;
    });

    try {
      // 获取查询参数
      final dateRange = _getDateRange();
      final dateType = _getDateType();
      
      final queryParams = {
        "dateType": dateType,
        "roomId": widget.roomId,
        "startDate": dateRange["startDate"],
        "endDate": dateRange["endDate"],
      };

      // 调用API接口
      final response = await checkInApi.getEleRecordByRoomId(widget.roomId, queryParams);
      
      if (response["data"] != null) {
        final data = response["data"] ?? [];

        if (data.isNotEmpty) {
          // 转换数据格式
          List<Map<String, dynamic>> newData = data.map((record) {
            return {
              "time": record["groupDate"] ?? "",
              "value": "${record["kwh"] ?? 0}度",
            };
          }).toList();
          setState(() {
            _records = newData;
            _isLoading = false;
          });
        } else {
          setState(() {
            _records = [];
            _isLoading = false;
          });
        }



      } else {
        // API调用失败
        setState(() {
          _records = [];
          _isLoading = false;
        });

        // 显示错误信息
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(response["message"] ?? "获取数据失败"),
              backgroundColor: Colors.red,
            ),
          );
        }
      }
    } catch (e) {
      setState(() {
        _records = [];
        _isLoading = false;
      });
      
      // 显示错误信息
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text("网络错误: $e"),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  // 下拉刷新
  Future<void> _onRefresh() async {
    await _fetchRecords();
  }

  // 获取时间范围
  Map<String, String> _getDateRange() {
    final year = _selectedDate.year;
    final month = _selectedDate.month;
    final day = _selectedDate.day;

    switch (_selectedType) {
      case "年":
        return {
          "startDate": "${year}-01-01 00:00:00",
          "endDate": "${year}-12-31 23:59:59",
        };
      case "月":
        // 获取月末日期
        final lastDay = DateTime(year, month + 1, 0).day;
        return {
          "startDate": "${year}-${month.toString().padLeft(2, '0')}-01 00:00:00",
          "endDate": "${year}-${month.toString().padLeft(2, '0')}-${lastDay.toString().padLeft(2, '0')} 23:59:59",
        };
      case "日":
        return {
          "startDate": "${year}-${month.toString().padLeft(2, '0')}-${day.toString().padLeft(2, '0')} 00:00:00",
          "endDate": "${year}-${month.toString().padLeft(2, '0')}-${day.toString().padLeft(2, '0')} 23:59:59",
        };
      default:
        return {
          "startDate": "${year}-01-01 00:00:00",
          "endDate": "${year}-12-31 23:59:59",
        };
    }
  }

  // 获取dateType参数
  String _getDateType() {
    switch (_selectedType) {
      case "年":
        return "year";
      case "月":
        return "month";
      case "日":
        return "day";
      default:
        return "year";
    }
  }

  // 显示日期选择器
  Future<void> _selectDate(BuildContext context) async {
    DateTime now = DateTime.now();
    DateTime? picked;
    switch (_selectedType) {
      case "年":
        picked = await showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text("选择年份"),
              content: SizedBox(
                height: 300,
                width: 300,
                child: YearPicker(
                  firstDate: DateTime(2020),
                  lastDate: DateTime(now.year),
                  selectedDate: _selectedDate,
                  onChanged: (DateTime dateTime) {
                    Navigator.pop(context, dateTime);
                  },
                ),
              ),
            );
          },
        );
        break;
      case "月":
        picked = await showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text("选择月份"),
              content: SizedBox(
                height: 300,
                width: 300,
                child: GridView.builder(
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3,
                    childAspectRatio: 2,
                  ),
                  itemCount: (_selectedDate.year == now.year) ? now.month : 12,
                  itemBuilder: (context, index) {
                    final month = index + 1;
                    return InkWell(
                      onTap: () {
                        Navigator.pop(
                          context,
                          DateTime(_selectedDate.year, month),
                        );
                      },
                      child: Center(
                        child: Text(
                          "$month月",
                          style: TextStyle(
                            color: month == _selectedDate.month
                                ? Theme.of(context).primaryColor
                                : Colors.black87,
                            fontWeight: month == _selectedDate.month
                                ? FontWeight.bold
                                : FontWeight.normal,
                          ),
                        ),
                      ),
                    );
                  },
                ),
              ),
            );
          },
        );
        break;
      case "日":
        DateTime lastDate;
        if (_selectedDate.year == now.year && _selectedDate.month == now.month) {
          // 如果是当前年月，限制到当前日期
          lastDate = now;
        } else if (_selectedDate.year > now.year || 
                   (_selectedDate.year == now.year && _selectedDate.month > now.month)) {
          // 如果选择的年月超过当前年月，限制到当前日期
          lastDate = now;
        } else {
          // 否则限制到选择月份的最后一天
          lastDate = DateTime(_selectedDate.year, _selectedDate.month + 1, 0);
        }
        
        picked = await showDatePicker(
          context: context,
          initialDate: _selectedDate,
          firstDate: DateTime(2020),
          lastDate: lastDate,
        );
        break;
    }

    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked!;
      });
      // 根据新的日期范围获取数据
      _fetchRecords();
    }
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "用电记录",
      child: Column(
        children: [
          // 年月日选择器
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.1),
                  spreadRadius: 1,
                  blurRadius: 2,
                  offset: const Offset(0, 1),
                ),
              ],
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                _buildDateTypeSelector("年"),
                _buildDateTypeSelector("月"),
                _buildDateTypeSelector("日"),
              ],
            ),
          ),
          // 时间显示（带左右切换按钮）
          Container(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 左按钮
                IconButton(
                  icon: const Icon(Icons.chevron_left),
                  onPressed: _canDecrease() ? _decreaseDate : null,
                ),
                const SizedBox(width: 8),
                Text(
                  _getDateDisplay(),
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(width: 8),
                // 右按钮
                IconButton(
                  icon: const Icon(Icons.chevron_right),
                  onPressed: _canIncrease() ? _increaseDate : null,
                ),
              ],
            ),
          ),
          // 列表内容
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : RefreshIndicator(
                    onRefresh: _onRefresh,
                    child: _records.isEmpty
                        ? const Center(
                            child: Text(
                              "暂无数据",
                              style: TextStyle(color: Colors.grey, fontSize: 16),
                            ),
                          )
                        : ListView.builder(
                            physics: const AlwaysScrollableScrollPhysics(),
                            itemCount: _records.length,
                            itemBuilder: (context, index) {
                              final item = _records[index];

                              return Container(
                                padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
                                decoration: BoxDecoration(
                                  border: Border(
                                    bottom: BorderSide(color: Colors.grey[200]!),
                                  ),
                                ),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(
                                      item["time"],
                                      style: const TextStyle(color: Colors.black87),
                                    ),
                                    Text(
                                      item["value"],
                                      style: const TextStyle(
                                        color: Colors.black87,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ],
                                ),
                              );
                            },
                          ),
                  ),
          ),
        ],
      ),
    );
  }

  Widget _buildDateTypeSelector(String type) {
    final isSelected = _selectedType == type;
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedType = type;
        });
        // 切换类型后重新获取数据
        _fetchRecords();
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 2.0),
        decoration: BoxDecoration(
          color: isSelected ? Theme.of(context).primaryColor : Colors.transparent,
          borderRadius: BorderRadius.circular(12.0),
          border: Border.all(
            color: isSelected ? Theme.of(context).primaryColor : Colors.grey[300]!,
            width: 1,
          ),
        ),
        child: Text(
          type,
          style: TextStyle(
            color: isSelected ? Colors.white : Colors.black87,
            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
            fontSize: 16,
          ),
        ),
      ),
    );
  }

  String _getDateDisplay() {
    final year = _selectedDate.year;
    final month = _selectedDate.month;
    final day = _selectedDate.day;

    switch (_selectedType) {
      case "年":
        return "$year年";
      case "月":
        return "$year年$month月";
      case "日":
        return "$year年$month月$day日";
      default:
        return "$year年";
    }
  }

  // 判断是否可以减少日期
  bool _canDecrease() {
    if (_selectedType == "年") {
      return _selectedDate.year > 2020;
    } else if (_selectedType == "月") {
      return !(_selectedDate.year == 2020 && _selectedDate.month == 1);
    } else if (_selectedType == "日") {
      return !(_selectedDate.year == 2020 && _selectedDate.month == 1 && _selectedDate.day == 1);
    }
    return true;
  }

  // 判断是否可以增加日期
  bool _canIncrease() {
    final now = DateTime.now();
    if (_selectedType == "年") {
      return _selectedDate.year < now.year;
    } else if (_selectedType == "月") {
      return !(_selectedDate.year == now.year && _selectedDate.month == now.month);
    } else if (_selectedType == "日") {
      // 如果选择的年月超过当前年月，不能增加
      if (_selectedDate.year > now.year || 
          (_selectedDate.year == now.year && _selectedDate.month > now.month)) {
        return false;
      }
      // 如果是当前年月，不能超过当前日期
      if (_selectedDate.year == now.year && _selectedDate.month == now.month) {
        return _selectedDate.day < now.day;
      }
      // 否则可以增加到该月的最后一天
      return true;
    }
    return true;
  }

  // 向前切换日期
  void _decreaseDate() {
    setState(() {
      if (_selectedType == "年") {
        _selectedDate = DateTime(_selectedDate.year - 1, _selectedDate.month, _selectedDate.day);
      } else if (_selectedType == "月") {
        if (_selectedDate.month == 1) {
          _selectedDate = DateTime(_selectedDate.year - 1, 12, _selectedDate.day);
        } else {
          _selectedDate = DateTime(_selectedDate.year, _selectedDate.month - 1, _selectedDate.day);
        }
        // 修正天数溢出
        final daysInMonth = DateTime(_selectedDate.year, _selectedDate.month + 1, 0).day;
        if (_selectedDate.day > daysInMonth) {
          _selectedDate = DateTime(_selectedDate.year, _selectedDate.month, daysInMonth);
        }
      } else if (_selectedType == "日") {
        _selectedDate = _selectedDate.subtract(const Duration(days: 1));
      }
    });
    // 切换日期后重新获取数据
    _fetchRecords();
  }

  // 向后切换日期
  void _increaseDate() {
    final now = DateTime.now();
    setState(() {
      if (_selectedType == "年") {
        if (_selectedDate.year < now.year) {
          _selectedDate = DateTime(_selectedDate.year + 1, _selectedDate.month, _selectedDate.day);
        }
      } else if (_selectedType == "月") {
        if (!(_selectedDate.year == now.year && _selectedDate.month == now.month)) {
          if (_selectedDate.month == 12) {
            _selectedDate = DateTime(_selectedDate.year + 1, 1, _selectedDate.day);
          } else {
            _selectedDate = DateTime(_selectedDate.year, _selectedDate.month + 1, _selectedDate.day);
          }
          // 修正天数溢出
          final daysInMonth = DateTime(_selectedDate.year, _selectedDate.month + 1, 0).day;
          if (_selectedDate.day > daysInMonth) {
            _selectedDate = DateTime(_selectedDate.year, _selectedDate.month, daysInMonth);
          }
        }
      } else if (_selectedType == "日") {
        // 如果选择的年月超过当前年月，不能增加
        if (_selectedDate.year > now.year || 
            (_selectedDate.year == now.year && _selectedDate.month > now.month)) {
          return;
        }
        // 如果是当前年月，不能超过当前日期
        if (_selectedDate.year == now.year && _selectedDate.month == now.month) {
          if (_selectedDate.day < now.day) {
            _selectedDate = _selectedDate.add(const Duration(days: 1));
          }
        } else {
          // 否则可以增加到该月的最后一天
          final nextDay = _selectedDate.add(const Duration(days: 1));
          final daysInMonth = DateTime(_selectedDate.year, _selectedDate.month + 1, 0).day;
          if (nextDay.day <= daysInMonth) {
            _selectedDate = nextDay;
          }
        }
      }
    });
    // 切换日期后重新获取数据
    _fetchRecords();
  }
}